// 公共js
import store from '../utils/vuex/store'
import api from '../api'
import session from '../utils/storage/session'

const common = {}

/**
 * @description 更新标题
 * @param {String} title 标题
 */
common.title = function (title) {
  const processTitle = process.env.APP_TITLE + '博客' || 'itSpire博客'
  window.document.title = `${title ? `${title} - ` : ''}${processTitle}`
}

/**
 * @description 打开新页面
 * @param {String} url 地址
 */
common.open = function (url) {
  var a = document.createElement('a')
  a.setAttribute('href', url)
  a.setAttribute('target', '_blank')
  a.setAttribute('id', 'd2admin-menu-link')
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(document.getElementById('d2admin-menu-link'))
}

/**
 * @description 弹框错误信息
 * @param msg
 */
common.error = function (msg) {
  ELEMENT.Message({
    message: msg,
    type: 'error',
    duration: 3 * 1000
  })
}

/**
 * @description 弹框成功信息
 * @param msg
 */
common.success = function (msg) {
  ELEMENT.Message({
    message: msg,
    type: 'success',
    duration: 2 * 1000
  })
}

common.loadingClose = function () {
  loading.close();
}

/**
 * @description 下划线转成驼峰 create_time -> createTime
 * @param str
 */
common.toHump = function (str) {
  return str.replace(/_(\w)/g, function (all, letter) {
    return letter.toUpperCase()
  })
}

/**
 * @description 驼峰转换下划线
 * @returns {string}
 */
common.toLine = function (str) {
  return str.replace(/([A-Z])/g, '_$1').toLowerCase()
}

/**
 * 数组去重
 * @param arr
 * @returns {any[]}
 */
common.arrayUnique = function (arr) {
  return [...new Set(arr)];
}

/**
 * 过滤对象空参数
 * @param val
 * @returns {{}}
 */
common.filterParam = function (val) {
  let data = {};
  for (let i in val) {
    if (val[i] !== "" && val[i] !== null && val[i] !== undefined) {
      data[i] = val[i]
    }
  }
  return data
}

/**
 * 禁止浏览器后退
 */
common.forbiddenForward = function () {  // 禁止浏览器后退
  history.pushState(null, null, document.URL);
  window.addEventListener('popstate', function () {
    history.pushState(null, null, document.URL);
  });
}

/**
 * 开关滚动条
 * @param className
 * @param option
 */
common.onOffScrollYByClassName = function (className, option = 'hidden') {
  document.getElementsByClassName(className)[0].style.overflowY = option
}

/**
 * 获取rsa公钥
 * @param val
 * @returns {Promise<*>}
 */
common.getPublicKey = async function (val = 'publicKey') {
  let key = session.get(val)
  if (key == null || key === '') {
    let res = await api.publicKey()
    key = res.publicKey
    session.set(val, key)
  }
  return key
}

common.escape2Html = function (str) {
  var arrEntities = {'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"'};
  return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all, t) {
    return arrEntities[t];
  });
}

/**
 * 格式化时间戳
 * @param timestamp
 * @returns {string}
 */
common.formatDate = function (value) {
  if (value == 0) {
    return '-';
  }
  var date = new Date(parseInt(value) * 1000)
  var Y = date.getFullYear() + '-'
  var M = zeroFill(date.getMonth() + 1) + '-'
  var D = zeroFill(date.getDate()) + ' '
  var h = zeroFill(date.getHours()) + ':'
  var m = zeroFill(date.getMinutes()) + ':'
  var s = zeroFill(date.getSeconds())
  return Y + M + D + h + m + s
}

/**
 * 格式化时间补0
 * @param i
 * @returns {*}
 */
function zeroFill(i) {
  if (i >= 0 && i <= 9) {
    return "0" + i
  } else {
    return i
  }
}

common.articleHot = async function () {
  if (!store.state.articleHot.length) {
    // store.state.articleHot = await api.articleHot()
    store.state.articleHot = [{"id":22,"title":"Flask SQLAlchemy原生sql的使用方法","readingNum":3633},{"id":41,"title":"Thinkphp5.0+Hui.Admin搭建的后台管理系统","readingNum":3557},{"id":20,"title":"Flask 获取post请求的json原始数据","readingNum":3340},{"id":44,"title":"Mac 触摸板实现鼠标中键（滚轮）的点击效果","readingNum":3060},{"id":61,"title":"Flask-SQLAlchemy 查询排序","readingNum":2422},{"id":23,"title":"Flask SQLAlchemy多数据库(指定数据库)执行原生sql","readingNum":2346}]
  }
  return store.state.articleHot
}

common.articleNew = async function () {
  if (!store.state.articleNew.length) {
    // store.state.articleNew = await api.articleNew()
    store.state.articleNew = [{"id":134,"title":"Golang 类型断言 x.(T) 以及 type switch 结构","publishTime":1608106141},{"id":133,"title":"websocket 通信 Uncaught (in promise) DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.","publishTime":1607486180},{"id":132,"title":"Vue 路由跳转页面不置顶","publishTime":1607316190},{"id":88,"title":"Vue 权限验证(动态路由)","publishTime":1605752680},{"id":131,"title":"PHPStorm Yaf框架代码追踪和提示","publishTime":1605692766},{"id":130,"title":"Vue 首次加载很慢，vendor文件过大优化","publishTime":1605609349}]
  }
  return store.state.articleNew
}

common.articleLabel = async function () {
  if (!store.state.articleLabel.length) {
    // store.state.articleLabel = await api.articleLabel()
    store.state.articleLabel = [{"id":15,"name":"php","count":40},{"id":18,"name":"linux","count":14},{"id":29,"name":"python","count":13},{"id":30,"name":"flask","count":11},{"id":43,"name":"vue","count":11},{"id":41,"name":"其他","count":10},{"id":42,"name":"go","count":10},{"id":26,"name":"设计模式","count":8},{"id":38,"name":"docker","count":8},{"id":17,"name":"mysql","count":7},{"id":31,"name":"git","count":6},{"id":36,"name":"redis","count":6},{"id":21,"name":"js","count":5},{"id":16,"name":"tp","count":5},{"id":28,"name":"html","count":5},{"id":54,"name":"nginx","count":4},{"id":27,"name":"ueditor","count":4},{"id":50,"name":"docker-compose","count":3},{"id":22,"name":"css","count":3},{"id":39,"name":"swoole","count":3}]
  }
  return store.state.articleLabel
}

common.commentNew = async function () {
  if (!store.state.commentNew.length) {
    // store.state.commentNew = await api.commentNew()
    store.state.commentNew = [{"id":14,"tid":0,"pid":0,"articleId":129,"userId":0,"nickname":"test2","content":"test","ip":0,"status":0,"createTime":0,"updateTime":0,"auditTime":0,"replyId":0,"replyNickname":"","contactType":0,"contact":"","title":"Webstorm 2020 永久激活破解","avatar":""},{"id":4,"tid":0,"pid":0,"articleId":116,"userId":0,"nickname":"晴小篆","content":"这个是一版本的操作办法， 现在早就使用2版本 gorm 了","ip":0,"status":0,"createTime":0,"updateTime":0,"auditTime":0,"replyId":0,"replyNickname":"","contactType":0,"contact":"","title":"Gorm 指定表前缀或指定表名","avatar":""},{"id":3,"tid":0,"pid":0,"articleId":22,"userId":0,"nickname":"‘’","content":"        '''\n        原生查询转字典\n\tobj 原生对象\n\t'''\n\t@staticmethod\n\tdef toDict(obj):\n\t\tres_list = [dict( zip( obj.keys()","ip":0,"status":0,"createTime":0,"updateTime":0,"auditTime":0,"replyId":0,"replyNickname":"","contactType":0,"contact":"","title":"Flask SQLAlchemy原生sql的使用方法","avatar":""}]
  }
  return store.state.commentNew
}

common.linkList = async function () {
  if (!store.state.linkList.length) {
    // store.state.linkList = await api.linkList()
    store.state.linkList = [{"id":1,"linkName":"itSpire","linkUrl":"http://www.itspire.cn"}]
  }
  return store.state.linkList
}

export default common


